package com.common.base.app.activity

import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.common.base.R
import com.common.base.app.extras.no
import com.common.base.app.extras.showToast
import com.common.base.app.extras.yes
import com.common.base.app.viewmodel.*
import com.common.base.utils.LogUtils

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/8/19
 * <p>
 * 描述：mvvm 基类
 * <p>
 * 修订历史：
 */
abstract class BaseVMActivity<VB : ViewBinding, VM : BaseViewModel> : BaseNavActivity<VB>() {
    companion object {
        val TAG: String = BaseVMActivity::class.java.simpleName
    }

    lateinit var mViewModel: VM

    override fun initViews() {
        mViewModel = ViewModelProvider(this, ViewModelFactory())[getViewModel()]
        initViewModelAction()
        super.initViews()
    }

    abstract fun getViewModel(): Class<VM>

    private fun initViewModelAction() {
        mViewModel.mStateLiveData.observe(this) { stateActionState ->
            when (stateActionState) {
                SuccessState -> {
                    loadFinish()
                    if (this !is BaseRecyclerVMActivity<*, *, *>) {
                        getPlaceholderView()?.isLoading()?.yes { showContent() }
                    }
                }

                is ErrorState -> {
                    LogUtils.e(TAG, "errorState: ${stateActionState.message}")
                    loadFinish()
                    showError()
                    showErrorToast(stateActionState.message)
//                    stateActionState.message?.apply { showToast(this) }
                }

                is ErrorStateAnMsg -> {
                    LogUtils.e(BaseVMActivity.TAG, "errorState: ${stateActionState.message}")
                    loadFinish()
                    showError()
                    showErrorToast("errorState: ${stateActionState.state}------> " + "errorMsg: ${stateActionState.message}")
                }

                else -> {}
            }
        }
        mViewModel.mFailureLiveData.observe(this) {
            isFinishing.no { loadingDialog?.get()?.dismiss() }
            loadFinish()
        }
    }

    open fun showErrorToast(msg: String? = null) {
    }


    /**
     * 默认错误提示
     */
    open fun showErrorMsg() {
//        Toast.makeText(this, "数据异常，请关闭页面后重新打开尝试！", Toast.LENGTH_SHORT).show();
        showToast(R.string.common_error_tip)
    }
}